# _*_ coding: UTF-8 _*_
# @Time     : 2022/4/22 17:32
# @Author   : Li Jie
# @Site     : http://www.cdtest.cn/
# @File     : prac.py
# @Software : PyCharm

# 实现京东的购物流程
# 打开京东，搜索商品，以销量排行，打开销量前5，切换到销量第二，上下翻页，选尺码，颜色，数量为5，加入购物车
# 点账号登录，输入账号密码，完成登录

from selenium import webdriver
import time
from selenium.webdriver.common.by import By


def foo1():
    driver = webdriver.Chrome()
    driver.maximize_window()

    driver.get("https://www.jd.com/")

    driver.find_element(By.ID, "key").send_keys("T恤")  # 输入搜索输入框
    driver.find_element(By.XPATH, '//*[@id="search"]/div/div[2]/button').click()  # 点击搜索按键
    time.sleep(2)

    driver.find_element(By.XPATH, '//*[@id="J_filter"]/div[1]/div[1]/a[2]').click()  # 点击销量
    time.sleep(2)

    # 循环打开销量前5
    for i in range(1, 6):
        driver.find_element(By.XPATH, f'//*[@id="J_goodsList"]/ul/li[{i}]/div/div[1]/a').click()

    # 切换到销量第二的产品
    handles = driver.window_handles
    for handle in handles:
        driver.switch_to.window(handle)
        if driver.current_url == "https://item.jd.com/10030434646509.html":
            break

    # 选择产品参数
    driver.find_element(By.XPATH, '//*[@id="choose-attr-1"]/div[2]/div[4]').click()  # 选款式

    for i in range(4):
        driver.find_element(By.XPATH, '//*[@id="choose-btns"]/div/div/a[2]').click()
    driver.find_element(By.XPATH, '//*[@id="choose-attr-2"]/div[2]/div[3]').click()  # 选尺码

    # 点击购物车
    driver.find_element(By.ID, 'InitCartUrl').click()
    time.sleep(2)

    # 点击账号登录
    driver.find_element(By.LINK_TEXT, '账户登录').click()
    time.sleep(1)

    # 输入账号和密码，点击登录
    driver.find_element(By.ID, 'loginname').send_keys("test")
    driver.find_element(By.ID, 'nloginpwd').send_keys('123456')
    driver.find_element(By.ID, 'loginsubmit').click()

    time.sleep(2)

    driver.quit()


if __name__ == "__main__":
    foo1()
